package com.cedifie.lendapp.ui.steps.fm

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.provider.ContactsContract
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmStepContactBinding
import com.cedifie.lendapp.http.ApiService.addCommonParams
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.ui.steps.act.CedStepAct
import com.cedifie.lendapp.ui.steps.adapter.CedStepContactAdapter
import com.cedifie.lendapp.utils.StringDeepCopy
import com.cedifie.lendapp.utils.decoration.LinearSpacingItemDecoration
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.lib.base.base.BaseFragment
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.log.LogHelper
import org.json.JSONArray
import org.json.JSONObject
import java.util.regex.Pattern

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime:  2024/6/18 14:46
 * @Annotation：流程 - 联系人信息
 */
class CedStepContactFm(): BaseFragment() {
    private var _binding: FmStepContactBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )

    private var authAct: CedStepAct? = null
    var data: JSONObject? = null
    //内容列表
    private var contactAdapter: CedStepContactAdapter? = null
    private var cedCacheContact = ""

    constructor(act: CedStepAct,data: JSONObject): this(){
        this.authAct = act
        this.data = data
    }

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmStepContactBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        initRvList()

        val showKey1 = getString(R.string.process_contact_info_tips_key1)
        val showKey2 = getString(R.string.process_contact_info_tips_key2)
        val showText = String.format(getString(R.string.process_contact_info_tips),showKey1,showKey2)
        val startIndex1 = showText.indexOf(showKey1)
        val startIndex2 = showText.indexOf(showKey2)
        val dataSecuritySpannable = SpannableString(showText)
        dataSecuritySpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF3263B0")), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        dataSecuritySpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF3263B0")), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.tvContactTips?.text = dataSecuritySpannable
    }

    override fun initCedListener() {
        //添加
        _binding?.btnAdd?.setOnClickListener {
            if (cedCacheContact.isNotEmpty()){
                LogHelper.e(">>>>>>>>>>>>添加一条>>>>>>>>>>>>>>>>")
                contactAdapter?.addLastItem(JSONObject(cedCacheContact))
                contactAdapter?.notifyDataSetChangedWrapper()
            }

            //最多添加50个联系人
            contactAdapter?.let {
                _binding?.btnAdd?.isEnabled = it.itemCount < 50
            }
        }
        //下一步
        _binding?.btnNext?.setOnClickListener {
            _binding?.root?.clearFocus()
            if (!isAllowSubmit()){
                showCedToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }
            data?.let {
                val params = JSONObject().addCommonParams().apply {
                    put("path",it.optString("apiUrl").replace("/",""))
                }
                //拼接上传数据格式
                val paramArray = JSONArray()
                contactAdapter?.let { adapter ->
                    for (i in 0..< adapter.itemCount){
                        val obj = JSONObject()
                        val dataArray = adapter.getItem(i).optJSONArray("dataList")
                        dataArray?.let { array ->
                            for (j in 0..< array.length()){
                                val item = array.optJSONObject(j)
                                val paramName = item.optString("paramName")
                                val selectItem = item.optJSONObject("selectItem")
                                var paramValue = selectItem?.optString("value")
                                if (paramName == "relation" && paramValue == item.optString("relationOtherKey")){
                                    paramValue = selectItem?.optString("otherValue")
                                    //如果关系为“Other”，输入的内容为纯数字，则直接传“Other”
                                    if (isCedOtherRelationAllNumber(paramValue)){
                                        paramValue = item.optString("relationOtherKey")
                                    }
                                }
                                obj.put(paramName,paramValue)
                            }
                        }
                        paramArray.put(obj)
                    }
                }
                params.put(it.optString("contactParamName"),paramArray)

                HttpHelper.addCedEventAction(String.format(CedEventType.CLICK.CED_CLICK_STEP_XX_NEXT,data?.optString("stepTitle")),"")
                //立即上报
                CedEventManager.getInstance().updateCedEventsNow()

                val act = context as CedStepAct
                act.onSubmitProcessAction(params)
            }
        }
    }

    override fun initCedData() {
        //联系人关系关键字
        val relationOther = getString(R.string.process_contact_info_relation_other)
        val relationOtherHint = getString(R.string.process_contact_info_relation_other_hint)
        //是否支持通讯录选择联系人
        val isContactPick = isPhoneBookPick()

        data?.let {
            val stepTitle = it.optString("stepTitle")
            // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
            val stringCopy = StringDeepCopy(it.optString("dataList"))
            val dataList = arrayListOf<JSONObject>()
            for (i in 0..< it.optInt("itemCount")){
                val obj = JSONObject()
                val dataArray = JSONArray(stringCopy.content)
                for (j in 0..<dataArray.length()){
                    val dataObj = dataArray.optJSONObject(j)
                    dataObj.put("isContactPick",isContactPick)
                    dataObj.put("title",dataObj.optString("title"))
                    when(dataObj.optString("action")){
                        "CONTACT_GROUP_RELATION",
                        "SELECT" -> {
                            dataObj.put("action","CONTACT_GROUP_RELATION")
                            val valueArray = it.optJSONArray("relationShips")?.optJSONArray(i)
                            valueArray?.let { array ->
                                if (!array.toString().contains(relationOther)){
                                    //手动添加一条Other
                                    array.put(relationOther)
                                }
                                val values = JSONArray()
                                for (n in 0..<array.length()){
                                    val value = JSONObject()
                                    value.put("title",array.optString(n))
                                    value.put("value",array.optString(n))
                                    values.put(value)
                                }
                                dataObj.put("values",values)
                            }
                            dataObj.put("relationOtherKey",relationOther)
                            dataObj.put("relationOtherHint",relationOtherHint)
                        }
                        "CONTACT_GROUP_PHONE" -> {//联系电话
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        "INPUT",
                        "CONTACT_GROUP_NAME" -> {//联系人姓名
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        else -> {
                            dataObj.put("action","INPUT")
                        }
                    }
                }
                obj.put("stepTitle",stepTitle)
                obj.put("dataList",dataArray)
                dataList.add(obj)
            }
            contactAdapter?.data = dataList
        }

        //缓存最后一个联系人item数据，用户新增item
        cedCacheContact = StringDeepCopy(contactAdapter?.lastItem.toString()).content
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_CONTACT_START,"")
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRvList() {
//        _binding?.recyclerView.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.recyclerView?.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        _binding?.recyclerView?.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        contactAdapter = CedStepContactAdapter(_binding?.recyclerView)
        contactAdapter?.parentView = _binding?.root
        _binding?.recyclerView?.adapter = contactAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        contactAdapter?.setOnContactSelectMobileListener(object : CedStepContactAdapter.ISelectMobileListener{
            override fun onSelectMobileClick(parentPosition: Int, childModel: JSONObject) {
                val startTime = System.currentTimeMillis()
                authAct?.chooseContact?.startPickContact{ contactName, contactMobile ->
                    LogHelper.e(">>>>>>>>>>>>>>>>>>>>>$contactName>>>>>>>$contactMobile")
                    val subTimestamp = System.currentTimeMillis() - startTime
                    val parentItem = contactAdapter?.getItem(parentPosition)
                    //设置联系人名称
                    val dataArray = parentItem?.optJSONArray("dataList")
                    if (dataArray != null) {
                        for (i in 0..<dataArray.length()) {
                            val itemObj = dataArray.optJSONObject(i)
                            if (itemObj.optString("paramName") == "fullName"){
                                val obj = JSONObject()
                                obj.put("title",contactName)
                                obj.put("value",contactName)
                                itemObj.put("selectItem",obj)
                                val subRemark = "${contactName}$$${subTimestamp}"
                                HttpHelper.addCedEventAction(String.format(CedEventType.CLICK.CED_CLICK_STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                continue
                            }
                            if (itemObj.optString("paramName") == "mobile"){
                                val obj = JSONObject()
                                obj.put("title",contactMobile)
                                obj.put("value",contactMobile)
                                itemObj.put("selectItem",obj)
                                val subRemark = "${contactMobile}$$${subTimestamp}"
                                HttpHelper.addCedEventAction(String.format(CedEventType.CLICK.CED_CLICK_STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                continue
                            }
                        }
                    }

//                    val obj = JSONObject()
//                    obj.put("title",contactMobile)
//                    obj.put("value",contactMobile)
//                    childModel.put("selectItem", obj)
                    contactAdapter?.notifyItemChanged(parentPosition)
                }
            }
        })
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        contactAdapter?.let { adapter ->
            for (i in 0..< adapter.itemCount){
                val dataArray = adapter.getItem(i).optJSONArray("dataList")
                dataArray?.let {
                    for (j in 0..< it.length()){
                        val item = it.optJSONObject(j)
                        dataList.add(item)
                    }
                }
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem")){
                isAllow = false
                break
            }
            val selectItem = item.optJSONObject("selectItem")
            if (selectItem == null){
                isAllow = false
                break
            }
            val paramName = item.optString("paramName")
            val paramValue = selectItem.optString("value")
            if (paramValue.isEmpty()){
                isAllow = false
                break
            }
            if (paramName == "relation" && paramValue == item.optString("relationOtherKey") && selectItem.optString("otherValue","").isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    /**
     * 是否支持通讯录选择
     */
    private fun isPhoneBookPick(): Boolean{
        val intentContact = Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        val resolveInfoCType = requireContext().packageManager.resolveActivity(intentContact, PackageManager.MATCH_DEFAULT_ONLY)
        return resolveInfoCType != null
    }

    /**
     * 是否全为数字
     */
    private fun isCedOtherRelationAllNumber(text: String?): Boolean {
        if (text.isNullOrEmpty()){
            return false
        }
        val formatLct = "^-?\\d+\\.?\\d*$"
        val patternLct = Pattern.compile(formatLct)
        return patternLct.matcher(text.trim()).matches()
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_CONTACT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}